var oracledb = require('oracledb');
oracledb.autoCommit = true;

var query = (sql, params) => {
    return new Promise((resolve, reject) => {
        oracledb.getConnection(
            {
                user: "LPM",
                password: "LPM",
                connectString: "192.168.12.5:1521/orcl"
            },
            function (err, connection) {
                if (err) {
                    console.error("err" + err.message);
                    return;
                }
                console.log('oracle数据库连接成功！！！');
                connection.execute(sql, params, function (err, result) {
                    if (err) {
                        console.error(err.message);
                        reject(err)
                        doRelease(connection);
                        return;
                    }
                    if (result.rowsAffected) {
                        resolve(result)
                    } else {
                        resolve(result.rows.map((v) => {
                            return result.metaData.reduce((p, key, i) => {
                                p[key.name] = v[i];
                                return p;
                            }, {})
                        }));
                    }
                    doRelease(connection);
                });
            }
        );
    })
}

function doRelease(connection) {
    connection.close(
        function (err) {
            if (err)
                console.error(err.message);
        });
}

exports.query = query;